import React, { Component } from 'react';
import ReactEcharts from "echarts-for-react";
import "echarts/lib/chart/line";
import "echarts/lib/component/tooltip";
import "echarts/lib/component/title"; // 此处是按需引入
import { searchPrescription ,searchSurroundNodes , searchSurroundNodesTopk , getDrugDiscribe } from './api/api';
import { AudioOutlined } from '@ant-design/icons';
import { Input, Space } from 'antd';
import emitter from './utils/events';


const { Search } = Input;


// var dataPath = '../data/text_vectors_afterNormalize'

// export const graphEventBus = new EventEmitter()
class MyForcemap extends Component {
    echartRef = {}
    constructor(props) {
        super(props);
        this.state= {
           data:[[]],
           categories : [],
           mark:['0', '1','2','3','4','5','6','7','8','9','10','11','12','13','14']
        }
    }

  componentDidMount() {
    // 组件装载完成以后声明一个自定义事件
    this.eventEmitter = emitter.addListener('resetPrescription', (message) => {
      debugger
        this.setState({
            data:message.data,
        });
    });
    this.eventEmitter2 = emitter.addListener('appendPrescription', (message) => {
      debugger
      this.appendNodes(message.data)
    });
  }
  componentWillUnmount() {
      emitter.removeListener(this.eventEmitter);
      emitter.removeListener(this.eventEmitter2);
  }

    getOption = () => {
        debugger
      // 组装数据，返回配置 option
      return{
        // 标题
        title: {
          text: '',
          subtext: '',
          top: 'top',
          left: 'left',
        },
        legend:{
          // data:['症状','方剂','药物'],
          right:"5%",
          bottom:"5%",
          orient:"vertical",
          data:[
            {name:"症状",icon:"circle"},
            {name:"方剂",icon:"rect"},
            {name:"药物",icon:"diamond"},
          ]
        },
        // hover显示内容
        tooltip: {
          trigger: 'item',
          triggerOn: 'none'
        },
        grid: [{
            show: false,
            backgroundColor: '#FEF8EF',
        }],
        
       
        animationDuration: 1500,
        animationEasingUpdate: 'quinticInOut',
        series: [
          {
            name: '',
            type: 'graph',
            layout: 'force',
            zoom:'0.5',
            // 极坐标系
            // coordinateSystem: 'polar',
            // coordinateSystem: 'cartesian2d',
            data: this.state.data[0],
            links: this.state.data[1],
            categories: this.state.data[2],
            draggable:true,
            friction : 0.6,
            // center: [0, 0],
            roam: "scale",
            itemStyle:{
              borderColor:"#001",
            },
            emphasis:{
              label:{
                show:true,
                formatter:function (params) {
                  // if (params.value.length > 1) {
                    return params.name
                  },
              }
            }
            ,
            label: {

              show: true,
              position: 'right',
              formatter:  function (params) {
                // if (params.value.length > 1) {
                  if (params.name.length > 4) {
                    return params.name.substr(0, 3) + '...'
                                  } else {
                    return params.name
                                  }
                },
                position:"inside",
              color: 'black',
              
              // backgroundColor: {
              //   image: 'https://picture.djwl.top/img/8ec34cb882dc4.jpg',
              // },
              // width: '30',
              // overflow: 'truncate',
            },
            lineStyle: {
              color: 'source',
              curveness: 0,
            },
            // itemStyle: {
            //   color: 'red',
            //   borderColor: 'red',
            // },
            // emphasis: {
            //   focus: 'adjacency',
            //   lineStyle: {
            //     width: 10,
            //   },
            // },
            // hover提示框
            // tooltip: {
            //   extraCssText:
            //     'width:200px;height:200px;background:white;color:black;padding:30px',
            // },
    
            force: {
              // initLayout: '',
              layoutAnimation:true,
              gravity: 0.02,
              repulsion: 2500,
              edgeLength: 400,
              friction:0.6,
            },
          },
        ],


      };
    }


    getDrugDis = async (params) => {
        let node_name = params["data"]["name"]

        let res = await getDrugDiscribe({node:node_name})
        if(res.code == 200){
            let drugDiscribe = {src:res.src,indications:res.indications,title:node_name}
            console.log(drugDiscribe)
            return drugDiscribe
        }
    }

    appendNodes = (params) => {
      debugger
      // let curData = this.state.data
      // emitter.emit("药物探索关联病症相关度",{nodes:res.search_polar_data.nodes,relativities:res.search_polar_data.relativities})
      // emitter.emit("addHighLightNodes",{highlight_nodes:res.highlight_nodes})

      let curData = this.echartRef.getEchartsInstance().getOption()["series"][0]["data"]
      let newData = JSON.parse(params)
      let curLink = this.echartRef.getEchartsInstance().getOption()["series"][0]["links"]

      let DATA = new Array()
      let mergeLinks = new Set()
      let mergeNodes = new Map()
      curData.forEach(x => mergeNodes.set(x["name"],x))
      newData["nodes"].forEach(x => mergeNodes.set(x["name"],x))
      let temparr = new Array()
      mergeNodes.forEach((v,k) => temparr.push(v))
      DATA.push(temparr)
      if (curLink != undefined){
        curLink.forEach(x => mergeLinks.add(x))
      }
      newData["links"].forEach(x => mergeLinks.add(x))
      let temp = new Array()
      for(let key of mergeLinks.keys()){
          temp.push(key)
      }
      DATA.push(temp)
      DATA.push(curData[2])
      console.log(DATA)
      // this.setState({data:DATA})
      this.echartRef.getEchartsInstance().setOption({
        series:{
          data: DATA[0],
          links: DATA[1],
          categories:newData["categories"],
        }
      });
    }
    addNodes = async (params) =>{
        let target_ = localStorage.getItem("target")
        let localDic = JSON.parse(localStorage.getItem("searchDic"))
        
        let res
        debugger
        // if(params["data"]["category"] == 2 &&( localDic[params["data"]["name"]] === undefined || localDic[params["data"]["name"]] === 0)){
          if(params["data"]["category"] == 2){
            // localDic[params["data"]["name"]] = 1
            // localStorage.setItem("searchDic",JSON.stringify(localDic))
            let relativity_ = localStorage.getItem("药物关联病症相关度")
           res = await searchSurroundNodesTopk({node:params["data"]["name"],target:target_,type:params["data"]["category"],relativity:relativity_})
        }else{
            // localDic[params["data"]["name"]] = 0
            // localStorage.setItem("searchDic",JSON.stringify(localDic))
           res = await searchSurroundNodes({node:params["data"]["name"],type:params["data"]["category"]})
        }
        
        if(res.code == 200){
            debugger
            // let curData = this.state.data
            emitter.emit("药物探索关联病症相关度",{nodes:res.search_polar_data.nodes,relativities:res.search_polar_data.relativities})
            emitter.emit("addHighLightNodes",{highlight_nodes:res.highlight_nodes})

            let curData = this.echartRef.getEchartsInstance().getOption()["series"][0]["data"]
            let newData = JSON.parse(res.data)
            let curLink = this.echartRef.getEchartsInstance().getOption()["series"][0]["links"]

            let DATA = new Array()
            let mergeLinks = new Set()
            let mergeNodes = new Map()
            curData.forEach(x => mergeNodes.set(x["name"],x))
            newData["nodes"].forEach(x => mergeNodes.set(x["name"],x))
            let temparr = new Array()
            mergeNodes.forEach((v,k) => temparr.push(v))
            DATA.push(temparr)
            curLink.forEach(x => mergeLinks.add(x))
            newData["links"].forEach(x => mergeLinks.add(x))
            let temp = new Array()
            for(let key of mergeLinks.keys()){
                temp.push(key)
            }
            DATA.push(temp)
            DATA.push(curData[2])
            console.log(DATA)
            // this.setState({data:DATA})
            this.echartRef.getEchartsInstance().setOption({
              series:{
                data: DATA[0],
                links: DATA[1],
              }
            });
        }
    }
    hideNodes = (params) =>{
      console.log("hide nodes")
      debugger
      let curData = this.echartRef.getEchartsInstance().getOption()["series"][0]["data"]
      let curLink = this.echartRef.getEchartsInstance().getOption()["series"][0]["links"]
      var target_flag = true
      var source_flag = true
      let newLink = new Array()
      let newData = new Array()
      for(var i = 0 ; i < curLink.length ; i++){
        if(curLink[i]["source"] === params.data["source"] && curLink[i]["target"] === params.data["target"]){
          continue
        }
        if(curLink[i]["source"] === params.data["source"] || curLink[i]["target"] === params.data["source"]){
          source_flag = false
        }
        if(curLink[i]["source"] === params.data["target"] || curLink[i]["target"] === params.data["target"]){
          target_flag = false
        }
        newLink.push(curLink[i])
      }
      for(var i = 0 ; i< curData.length ; i++){
        if(source_flag && curData[i]["name"] === params.data["source"]){
          continue
        }
        if(target_flag && curData[i]["name"] === params.data["target"]){
          continue
        }
        newData.push(curData[i])
      }
      this.echartRef.getEchartsInstance().setOption({
        series:{
          data: newData,
          links: newLink,
        }
      });
    }

    render() {
       let EventsDict = {
            'click':(params)=>{
              
              if(params.dataType === "node"){
                this.addNodes(params)
              }else if(params.dataType === "edge"){
                this.hideNodes(params)
              }
              
            },
            'mouseup':(params)=>{
              let curOptions = this.echartRef.getEchartsInstance().getOption()
              curOptions.series[0].data[params.dataIndex].x = params.event.offsetX
              curOptions.series[0].data[params.dataIndex].y = params.event.offsetY
              curOptions.series[0].data[params.dataIndex].fixed = true;
              console.log(params.event.offsetX , params.event.offsetY)
              this.echartRef.getEchartsInstance().setOption(curOptions)
            },
            'mouseover':(params)=>{
              debugger
              if(params.dataType === "node"){
                if( params.data.category === 1){
                  let curOptions = this.echartRef.getEchartsInstance().getOption()
                  let title = null
                  for(var i = 0 ; i < curOptions.series[0].links.length ; i++){
                    if(curOptions.series[0].links[i]['target'] === params.data.name){
                      title = curOptions.series[0].links[i]['source']
                    }
                  }
                  debugger
                  emitter.emit('changePrescription', {title:title,content:params.data.name});
                }else if(params.data.category === 2){
                  this.getDrugDis(params).then((data)=>{
                    emitter.emit('changeDrug', {title:data.title,src:data.src,indications:data.indications});
                  })
                }
                
              }
            }
        }
      return(
        <div style={{textAlign:"left"}}>
        <ReactEcharts
        ref={e => this.echartRef = e}
          style={{ minHeight: "650px" ,marginTop:"12%"}}
          option={this.getOption()}
          notMerge = {true}
          theme={"theme_name"}
          // onChartReady={this.onChartReadyCallback}
          onEvents={EventsDict}
        />
        </div>
        
      )
    }
}
 
export default MyForcemap;